package qc.module.ehs.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.EhsHazardPreventTypeEnum;
import qc.common.core.enums.EhsRiskLevelEnum;
import qc.common.core.enums.TimeRangeLengthEnum;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.common.core.utils.DateUtil;
import qc.common.core.utils.IdentifierUtil;
import qc.module.ehs.dto.hazard.*;
import qc.module.ehs.entity.EhsHazardPreventrecord;
import qc.module.ehs.entity.EhsTplHazarddb;
import qc.module.ehs.entity.EhsUnitBasic;
import qc.module.ehs.entity.EhsUnitIdentificationRecord;
import qc.module.ehs.mapper.EhsUnitBasicMapper;
import qc.module.ehs.repository.EhsTplHazarddbRepository;
import qc.module.ehs.repository.EhsUnitBasicRepository;
import qc.module.ehs.repository.EhsUnitIdentificationRecordRepository;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 单元危险源辨识记录信息Service
 *
 * @author QuCheng Tech
 * @create 2024/6/13
 */
@Service
public class EhsUnitIdentificationRecordService {
    
    @Autowired
    private EhsUnitIdentificationRecordRepository repository;
    
    @Autowired
    private EhsUnitBasicRepository unitBasicRepository;
    
    @Autowired
    private EhsTplHazarddbRepository hazarddbRepository;

    @Autowired
    private EhsHazardBasicService hazardBasicService;
    
    @Autowired
    private EhsHazardPreventrecordService hazardPreventrecordService;

    //时间范围类型；默认按月
    private final Integer TIME_RANGE = TimeRangeLengthEnum.MONTH.getIndex();
    
    /**
     * 按单元查询危险源：
     * 1.判断查询条件；
     * 2.根据查询条件“组织代码”查询单元unitBasics;
     * 3.如果unitBasics为空，直接返回null；否则转换为单元危险源结果项resultItemDtos；
     * 4.从resultItemDtos获取单元ID集合，根据单元ID集合、查询条件“辨识起止时间”查询单元危险源记录unitIdentificationRecords；
     * 5.将记录相关信息整合到resultItemDtos中；
     * 6.将危险源结果项resultItemDto构建为树型结构items；
     * 7.从items中过滤符合查询条件“是否为在建工程、是否根据用户部门进行过滤”的结果项（从子级开始向上筛选，子级符合条件，父级一并返回）；
     * 8.统计查询结果合计值（只统计根节点数据）；
     * 9.设置返回结果
     *
     * @param condition 查询条件
     * @param deptIds 当前用户所属部门集合
     * @return QueryHazardByUnitResultDto
     * @author QuCheng Tech
     * @since 2024/6/14
     */
    public QueryHazardByUnitResultDto queryByUnit(QueryHazardByUnitConditionDto condition,List<Integer> deptIds) throws QCPromptException {
        //1.条件判断
        if (condition == null) throw new QCPromptException("查询条件不能为空");
        if (StringUtils.isBlank(condition.getOrgcode())) throw new QCPromptException("组织代码不能为空");
        
        //查询时间处理
        Date beginDate = null;
        Date endDate = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getBegintm())) {
            try {
                beginDate = DateUtil.parseDate(condition.getBegintm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的开始日期转换错误");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(condition.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的截止日期转换错误");
            }
        }

        Date beginTime = beginDate;
        Date endTime = endDate;
        if (condition.getTmtype() == null) condition.setTmtype(TIME_RANGE);
        if (condition.getTmtype() == TimeRangeLengthEnum.MONTH.getIndex()){
            //按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }else if (condition.getTmtype() == TimeRangeLengthEnum.QUARTER.getIndex()){
            //按季度：根据开始时间处理为开始时间所在季度的第一天，根据结束时间处理为结束时间所在季度最后一天
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x0, 0x1);
            int beginTimeMonth = DateUtil.getMonth(beginDate);
            if (beginTimeMonth >= 10)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x9, 0x1);
            else if (beginTimeMonth >= 7)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x6, 0x1);
            else if (beginTimeMonth >= 4)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x3, 0x1);

            //先计算结束时间所在季度的开始时间endtmbegin，再根据endtmbegin计算结束时间
            Date endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x0, 0x1);
            int endTimeMonth = DateUtil.getMonth(endDate);
            if (endTimeMonth >= 10)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x9, 0x1);
            else if (endTimeMonth >= 7)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x6, 0x1);
            else if (endTimeMonth >= 4)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x3, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endtmbegin, 0x3), -1);
            
        }else{
            //默认按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }
        
        //2.根据查询条件查询单元
        LambdaQueryWrapper<EhsUnitBasic> unitWrapper = new LambdaQueryWrapper<>();
        unitWrapper.eq(EhsUnitBasic::getOrgcode,condition.getOrgcode());
        unitWrapper.orderByAsc(EhsUnitBasic::getOdr,EhsUnitBasic::getUnitname);
        List<EhsUnitBasic> unitBasics = unitBasicRepository.selectList(unitWrapper);
        if (CollectionUtils.isEmpty(unitBasics)) return null;
        
        //3.unitEns转换为QueryHazardByUnitResultItemDtos，获取单元ID集合
        List<QueryHazardByUnitResultItemDto> resultItemDtos = EhsUnitBasicMapper.MAPPER.toHazardByUnitResultItemTreeDtoList(unitBasics);
        List<String> unitIds = resultItemDtos.stream().map(QueryHazardByUnitResultItemDto::getUnitid).collect(Collectors.toList());

        //4.根据查询条件“时间范围类型、辨识起始时间、辨识截止时间”与单元ID集合查询单元危险源辨识记录
        LambdaQueryWrapper<EhsUnitIdentificationRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.in(EhsUnitIdentificationRecord::getUnitid,unitIds);
        //判断时间范围类型、辨识起止时间
        recordWrapper.eq(EhsUnitIdentificationRecord::getTmtype,condition.getTmtype());
        recordWrapper.ge(EhsUnitIdentificationRecord::getTmbegin, beginTime);
        recordWrapper.le(EhsUnitIdentificationRecord::getTmend, endTime);
        recordWrapper.orderByAsc(EhsUnitIdentificationRecord::getUpdatetm);
        List<EhsUnitIdentificationRecord> unitIdentificationRecords = repository.selectList(recordWrapper);
        
        //5.将查询记录结果设置到危险源结果项resultItemDtos中
        if (CollectionUtils.isNotEmpty(unitIdentificationRecords)){
            for (QueryHazardByUnitResultItemDto resultItemDto : resultItemDtos){
                for (EhsUnitIdentificationRecord record : unitIdentificationRecords){
                    if (resultItemDto.getUnitid().equals(record.getUnitid())){
                        resultItemDto.setTmstr(record.getTmstr());
                        if (record.getFlag()){
                            resultItemDto.setStatus(0x1);
                        }
                        else {
                            resultItemDto.setStatus(0x0);
                        }
                        resultItemDto.setGeneral1(record.getGeneral1());
                        resultItemDto.setMajor1(record.getMajor1());
                        resultItemDto.setLevel11(record.getLevel11());
                        resultItemDto.setLevel12(record.getLevel12());
                        resultItemDto.setLevel13(record.getLevel13());
                        resultItemDto.setLevel14(record.getLevel14());
                        resultItemDto.setGeneral2(record.getGeneral2());
                        resultItemDto.setMajor2(record.getMajor2());
                        resultItemDto.setLevel21(record.getLevel21());
                        resultItemDto.setLevel22(record.getLevel22());
                        resultItemDto.setLevel23(record.getLevel23());
                        resultItemDto.setLevel24(record.getLevel24());
                        resultItemDto.setTmbegin(DateUtil.getDateMonthString(record.getTmbegin()));
                        resultItemDto.setTmend(DateUtil.getDateMonthString(record.getTmend()));
                        resultItemDto.setTmstr(record.getTmstr());
                    }
                }
            }
        }
        
        //6.将危险源结果项resultItemDtos构建为树型结构items
        List<QueryHazardByUnitResultItemDto> items = new ArrayList<>();
        //获取根节点集合（parentid为空）
        List<QueryHazardByUnitResultItemDto> rootItems = resultItemDtos.stream().
                filter(p -> StringUtils.isEmpty(p.getParentid())).collect(Collectors.toList());
        //获取子节点
        if (CollectionUtils.isNotEmpty(rootItems)) items = getSubItems(resultItemDtos,rootItems);
        
        //7.从items中过滤符合查询条件“是否为在建工程、是否根据用户部门进行过滤”的结果项
        Iterator<QueryHazardByUnitResultItemDto> rootLevelIterator = items.iterator();
        while (rootLevelIterator.hasNext()){
            QueryHazardByUnitResultItemDto rootlevel = rootLevelIterator.next();

            //子级结果筛选
            if (rootlevel.getChildren() != null && rootlevel.getChildren().size() > 0x0){
                filterSubTreeTableResult(rootlevel,condition,deptIds);
            }
            //当前层级筛选
            //是否移除
            boolean isRemoveRootLevel = false;
            if (rootlevel.getChildren() == null || rootlevel.getChildren().size() == 0x0){
                //是否为在建工程：为0表示false，为1表示true，为空或其他时表示不管该标记状态
                if (StringUtils.isNotBlank(condition.getIsconstruction())){
                    if (condition.getIsconstruction().equals("0")){
                        if (rootlevel.getIsconstruction() == true) isRemoveRootLevel = true;
                    }else if (condition.getIsconstruction().equals("1")){
                        if (rootlevel.getIsconstruction() == false) isRemoveRootLevel = true;
                    }
                }
                //是否根据用户部门进行过滤:为true表示根据当前用户所关联部门对单元进行筛选过滤，为false表示不过滤
                if (condition.getIsdept()){
                    if (CollectionUtils.isNotEmpty(deptIds)){
                        boolean deptIsExist = false;//level4的部门是否匹配用户部门
                        for (Integer deptId : deptIds){
                            if (deptId == rootlevel.getDeptid()){
                                deptIsExist = true;
                            }
                        }
                        if (!deptIsExist) isRemoveRootLevel = true;
                    }
                }
                
                if (isRemoveRootLevel) rootLevelIterator.remove();
            }
        }

        //8.结果统计中各统计值记录
        Integer general1 = 0x0,major1 = 0x0,level11 = 0x0,level12 = 0x0,level13 = 0x0,level14 = 0x0,
                general2 = 0x0,major2 = 0x0,level21 = 0x0,level22 = 0x0,level23 = 0x0,level24 = 0x0;
        for (QueryHazardByUnitResultItemDto itemDto : items){
            //计算根节点各数量合计值
            general1 += itemDto.getGeneral1();
            major1 += itemDto.getMajor1();
            level11 += itemDto.getLevel11();
            level12 += itemDto.getLevel12();
            level13 += itemDto.getLevel13();
            level14 += itemDto.getLevel14();
            general2 += itemDto.getGeneral2();
            major2 += itemDto.getMajor2();
            level21 += itemDto.getLevel21();
            level22 += itemDto.getLevel22();
            level23 += itemDto.getLevel23();
            level24 += itemDto.getLevel24();
        }
        
        //9.设置返回结果
        QueryHazardByUnitResultDto result = new QueryHazardByUnitResultDto();
        result.setItems(items);
        result.setGeneral1(general1);
        result.setMajor1(major1);
        result.setLevel11(level11);
        result.setLevel12(level12);
        result.setLevel13(level13);
        result.setLevel14(level14);
        result.setGeneral2(general2);
        result.setMajor2(major2);
        result.setLevel21(level21);
        result.setLevel22(level22);
        result.setLevel23(level23);
        result.setLevel24(level24);
        return result;
    }

    /**
     * 递归获取子级单元危险源信息
     *
     * @param resultItemDtos 所有单元危险源信息
     * @param parentItems 父级单元危险源信息
     * @return List<QueryHazardByUnitResultItemDto>
     * @author QuCheng Tech
     * @since 2024/6/14
     */
    private List<QueryHazardByUnitResultItemDto> getSubItems(List<QueryHazardByUnitResultItemDto> resultItemDtos,
                                                             List<QueryHazardByUnitResultItemDto> parentItems){
        List<QueryHazardByUnitResultItemDto> items = new ArrayList<>();

        if (CollectionUtils.isEmpty(resultItemDtos)) return null;

        if (CollectionUtils.isNotEmpty(parentItems)){
            for (QueryHazardByUnitResultItemDto pItem : parentItems){
                //获取子级单元信息集合
                List<QueryHazardByUnitResultItemDto> subItems = resultItemDtos.stream().filter(p -> 
                        pItem.getUnitid().equals(p.getParentid())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(subItems)){
                    getSubItems(resultItemDtos,subItems);
                    pItem.setChildren(subItems);
                }

                //统计数量为空的设置返回0
                if (pItem.getGeneral1() == null) pItem.setGeneral1(0x0);
                if (pItem.getMajor1() == null) pItem.setMajor1(0x0);
                if (pItem.getLevel11() == null) pItem.setLevel11(0x0);
                if (pItem.getLevel12() == null) pItem.setLevel12(0x0);
                if (pItem.getLevel13() == null) pItem.setLevel13(0x0);
                if (pItem.getLevel14() == null) pItem.setLevel14(0x0);
                if (pItem.getGeneral2() == null) pItem.setGeneral2(0x0);
                if (pItem.getMajor2() == null) pItem.setMajor2(0x0);
                if (pItem.getLevel21() == null) pItem.setLevel21(0x0);
                if (pItem.getLevel22() == null) pItem.setLevel22(0x0);
                if (pItem.getLevel23() == null) pItem.setLevel23(0x0);
                if (pItem.getLevel24() == null) pItem.setLevel24(0x0);
                
                items.add(pItem);
            }
        }
        
        
        
        return items;
    }

    /**
     * 递归过滤单元危险源结果项的子级结果
     *
     * @param rootLevel 父层级单元危险源结果项
     * @param condition 过滤条件
     * @param deptIds 当前用户所属部门集合
     * @author QuCheng Tech
     * @since 2024/6/14
     */
    private void filterSubTreeTableResult(QueryHazardByUnitResultItemDto rootLevel,
                                          QueryHazardByUnitConditionDto condition, List<Integer> deptIds){
        Iterator<QueryHazardByUnitResultItemDto> subLevelIterator = rootLevel.getChildren().iterator();
        while (subLevelIterator.hasNext()){
            QueryHazardByUnitResultItemDto subLevel = subLevelIterator.next();

            if (subLevel.getChildren() != null && subLevel.getChildren().size() > 0x0){
                filterSubTreeTableResult(subLevel,condition,deptIds);
            }

            if (subLevel.getChildren() == null || subLevel.getChildren().size() == 0x0){
                //是否移除
                boolean isRemoveSubLevel = false;
                //是否为在建工程：为0表示false，为1表示true，为空或其他时表示不管该标记状态
                if (StringUtils.isNotBlank(condition.getIsconstruction())){
                    if (condition.getIsconstruction().equals("0")){
                        if (subLevel.getIsconstruction() == true) isRemoveSubLevel = true;
                    }else if (condition.getIsconstruction().equals("1")){
                        if (subLevel.getIsconstruction() == false) isRemoveSubLevel = true;
                    }
                }
                //是否根据用户部门进行过滤:为true表示根据当前用户所关联部门对单元进行筛选过滤，为false表示不过滤
                if (condition.getIsdept()){
                    if (CollectionUtils.isNotEmpty(deptIds)){
                        boolean deptIsExist = false;//level4的部门是否匹配用户部门
                        for (Integer deptId : deptIds){
                            if (deptId == subLevel.getDeptid()){
                                deptIsExist = true;
                            }
                        }
                        if (!deptIsExist) isRemoveSubLevel = true;
                    }
                }

                if (isRemoveSubLevel) subLevelIterator.remove();
            }
        }
    }



    /**
     * 指定单元查询指定周期危险源
     *
     * @param condition 查询条件
     * @param hdbcd 导则库编码
     * @return QueryOneUnitHazardResultDto
     * @author QuCheng Tech
     * @since 2024/7/2
     */
    public QueryOneUnitHazardResultDto getOneUnit(QueryOneUnitHazardConditionDto condition,String hdbcd) throws QCPromptException, ParseException {
        //1.条件判空
        if (condition == null) throw new QCPromptException("条件不能为空");
        if (StringUtils.isBlank(condition.getUnitid())) throw new QCPromptException("单元ID不能为空");
        if ((StringUtils.isBlank(condition.getBegintm()))) throw new QCPromptException("辨识起始时间不能为空");
        if (StringUtils.isBlank(condition.getEndtm())) throw new QCPromptException("辨识截止时间不能为空");

        //查询时间处理
        Date beginDate = null;
        Date endDate = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getBegintm())) {
            try {
                beginDate = DateUtil.parseDate(condition.getBegintm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的开始日期转换错误");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(condition.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的截止日期转换错误");
            }
        }

        Date beginTime = beginDate;
        Date endTime = endDate;
        if (condition.getTmtype() == null) condition.setTmtype(TIME_RANGE);
        if (condition.getTmtype() == TimeRangeLengthEnum.MONTH.getIndex()){
            //按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }else if (condition.getTmtype() == TimeRangeLengthEnum.QUARTER.getIndex()){
            //按季度：根据开始时间处理为开始时间所在季度的第一天，根据结束时间处理为结束时间所在季度最后一天
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x0, 0x1);
            int beginTimeMonth = DateUtil.getMonth(beginDate);
            if (beginTimeMonth >= 10)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x9, 0x1);
            else if (beginTimeMonth >= 7)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x6, 0x1);
            else if (beginTimeMonth >= 4)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x3, 0x1);

            //先计算结束时间所在季度的开始时间endtmbegin，再根据endtmbegin计算结束时间
            Date endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x0, 0x1);
            int endTimeMonth = DateUtil.getMonth(endDate);
            if (endTimeMonth >= 10)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x9, 0x1);
            else if (endTimeMonth >= 7)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x6, 0x1);
            else if (endTimeMonth >= 4)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x3, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endtmbegin, 0x3), -1);
        }else{
            //默认按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }
        
        
        //2.获取指定单元信息
        EhsUnitBasic unitBasic = unitBasicRepository.selectById(condition.getUnitid());
        if (unitBasic == null) return null;
        
        //3.获取指定单元指定周期单元危险源辨识记录信息，如果有记录，设置返回结果信息
        //3.1 返回结果对象创建
        QueryOneUnitHazardResultDto resultDto = new QueryOneUnitHazardResultDto();
        if (condition.getTmtype() == null) condition.setTmtype(TIME_RANGE);
        EhsUnitIdentificationRecord unitIdentificationRecord = getUnitTmRecord(condition.getUnitid(),condition.getBegintm(),condition.getEndtm(),condition.getTmtype());
        if (unitIdentificationRecord != null){
            //3.2 有记录，设置返回结果对象属性值
            resultDto.setTmbegin(DateUtil.getDateMonthString(unitIdentificationRecord.getTmbegin()));
            resultDto.setTmend(DateUtil.getDateMonthString(unitIdentificationRecord.getTmend()));
            resultDto.setTmstr(unitIdentificationRecord.getTmstr());
            //辨识状态
            if (unitIdentificationRecord.getFlag()){
                resultDto.setStatus(0x1);//已完成
            }else {
                resultDto.setStatus(0x0);//辨识中
            }
            resultDto.setUnitid(unitIdentificationRecord.getUnitid());
            resultDto.setUnitname(unitBasic.getUnitname());
            resultDto.setUnittype(unitBasic.getUnittype().getIndex());
            resultDto.setUnitlevel(unitBasic.getUnitlevel());
            resultDto.setIsconstruction(unitBasic.getIsconstruction());
            resultDto.setGeneral1(unitIdentificationRecord.getGeneral1());
            resultDto.setMajor1(unitIdentificationRecord.getMajor1());
            resultDto.setLevel11(unitIdentificationRecord.getLevel11());
            resultDto.setLevel12(unitIdentificationRecord.getLevel12());
            resultDto.setLevel13(unitIdentificationRecord.getLevel13());
            resultDto.setLevel14(unitIdentificationRecord.getLevel14());
            resultDto.setGeneral2(unitIdentificationRecord.getGeneral2());
            resultDto.setMajor2(unitIdentificationRecord.getMajor2());
            resultDto.setLevel21(unitIdentificationRecord.getLevel21());
            resultDto.setLevel22(unitIdentificationRecord.getLevel22());
            resultDto.setLevel23(unitIdentificationRecord.getLevel23());
            resultDto.setLevel24(unitIdentificationRecord.getLevel24());
            //3.3 如果导则库编码不为空，获取指定导则库信息，设置为返回结果对象属性值
            if (StringUtils.isNotBlank(hdbcd)){
                EhsTplHazarddb db = hazarddbRepository.selectById(hdbcd);
                resultDto.setHdbcd(db.getHdbcd());
                resultDto.setHdbnm(db.getHdbnm());
            }

            //4.获取危险源完整信息集合（危险源基础信息、辨识信息、评价信息）
            List<EhsHazardFullInfoDto> hazards = new ArrayList<>();
            //4.1 获取指定单元的危险源基础信息集合
            List<EhsHazardBasicDto> hazardBasicDtos = hazardBasicService.getByUnitId(condition.getUnitid());
            if (CollectionUtils.isNotEmpty(hazardBasicDtos)){
                List<String> hazardIds = hazardBasicDtos.stream().map(EhsHazardBasicDto::getHazardid).collect(Collectors.toList());
                //4.2 获取危险源辨识信息集合
                List<EhsHazardPreventrecord> identificationecords = hazardPreventrecordService.getRecords(hazardIds,
                        EhsHazardPreventTypeEnum.IDENTIFICATION.getIndex(),beginTime,endTime,condition.getTmtype());
                //4.3 获取危险源评价信息集合
                List<EhsHazardPreventrecord> evaluationRecords = hazardPreventrecordService.getRecords(hazardIds,
                        EhsHazardPreventTypeEnum.EVALUATION.getIndex(),beginTime,endTime,condition.getTmtype());

                //4.4 整合危险源完整信息（基础、辨识、评价）
                for (EhsHazardBasicDto basicDto : hazardBasicDtos){
                    EhsHazardFullInfoDto hazard = new EhsHazardFullInfoDto();
                    HazardIdentificationDto identification = new HazardIdentificationDto();
                    HazardRiskEvaluationDto evaluation = new HazardRiskEvaluationDto();
                    
                    if (CollectionUtils.isNotEmpty(identificationecords)){
                        for (EhsHazardPreventrecord preventRecord : identificationecords){
                            if (basicDto.getHazardid().equals(preventRecord.getHazardid())){
                                identification.setHazardid(preventRecord.getHazardid());
                                identification.setSubunitcode(basicDto.getUnitname());
                                identification.setPosition(basicDto.getPosition());
                                identification.setIsreport(basicDto.getIsreport());
                                identification.setDescription(preventRecord.getDescription());
                                //identification.setResult(preventRecord.getResultormethod());
                                identification.setUndercontrol(preventRecord.getUndercontrol());
                                identification.setUnsafefactor(preventRecord.getUnsafefactor());
                                identification.setFinalresult(preventRecord.getConafterhazardcategory());
                                identification.setTmbegin(DateUtil.getDateMonthString(preventRecord.getTmbegin()));
                                identification.setTmend(DateUtil.getDateMonthString(preventRecord.getTmend()));
                                identification.setTmstr(unitIdentificationRecord.getTmstr());
                                identification.setByuser(preventRecord.getConusername());
                                identification.setInuser(preventRecord.getInuser());
                                identification.setIntm(DateUtil.getDateTimeString(preventRecord.getIntm()));
                            }
                        }
                    }
                    
                    if (CollectionUtils.isNotEmpty(evaluationRecords)){
                        for (EhsHazardPreventrecord preventRecord : evaluationRecords){
                            if (basicDto.getHazardid().equals(preventRecord.getHazardid())){
                                evaluation.setHazardid(preventRecord.getHazardid());
                                evaluation.setMethod(preventRecord.getResultormethod());
                                evaluation.setRisklevel(preventRecord.getConafterrisklevel());
                                evaluation.setContent(preventRecord.getConresultdes());
                                evaluation.setTmbegin(DateUtil.getDateMonthString(preventRecord.getTmbegin()));
                                evaluation.setTmend(DateUtil.getDateMonthString(preventRecord.getTmend()));
                                evaluation.setTmstr(preventRecord.getTmstr());
                                evaluation.setByuser(preventRecord.getConusername());
                                evaluation.setInuser(preventRecord.getInuser());
                                evaluation.setIntm(DateUtil.getDateTimeString(preventRecord.getIntm()));
                            }
                        }
                    }
                    hazard.setBasic(basicDto);
                    hazard.setIdentification(identification);
                    hazard.setEvaluation(evaluation);
                    hazards.add(hazard);
                }
            }
            //4.5 设置危险源完整信息集合，返回结果
            resultDto.setHazards(hazards);
            return resultDto;
        }
        
        return null;
    }

    /**
     * 获取指定单元指定周期单元危险源辨识记录信息
     *
     * @param unitId 单元ID
     * @param tmbegin 辨识周期起始时间
     * @param tmend 辨识周期截止时间
     * @return EhsUnitIdentificationRecord
     * @author QuCheng Tech
     * @since 2024/6/28
     */
    public EhsUnitIdentificationRecord getUnitTmRecord(String unitId,String tmbegin,String tmend,Integer tmtype) throws ParseException, QCPromptException {
        //查询时间处理
        Date beginDate = null;
        Date endDate = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(tmbegin)) {
            try {
                beginDate = DateUtil.parseDate(tmbegin);
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的开始日期转换错误");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(tmend)) {
            try {
                endDate = DateUtil.parseDate(tmend);
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的截止日期转换错误");
            }
        }
        
        Date beginTime = beginDate;
        Date endTime = endDate;
        if (tmtype == TimeRangeLengthEnum.MONTH.getIndex()){
            //按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }else if (tmtype == TimeRangeLengthEnum.QUARTER.getIndex()){
            //按季度：根据开始时间处理为开始时间所在季度的第一天，根据结束时间处理为结束时间所在季度最后一天
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x0, 0x1);
            int beginTimeMonth = DateUtil.getMonth(beginDate);
            if (beginTimeMonth >= 10)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x9, 0x1);
            else if (beginTimeMonth >= 7)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x6, 0x1);
            else if (beginTimeMonth >= 4)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x3, 0x1);

            //先计算结束时间所在季度的开始时间endtmbegin，再根据endtmbegin计算结束时间
            Date endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x0, 0x1);
            int endTimeMonth = DateUtil.getMonth(endDate);
            if (endTimeMonth >= 10)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x9, 0x1);
            else if (endTimeMonth >= 7)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x6, 0x1);
            else if (endTimeMonth >= 4)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x3, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endtmbegin, 0x3), -1);
        }else{
            //默认按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }
        
        LambdaQueryWrapper<EhsUnitIdentificationRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(EhsUnitIdentificationRecord::getUnitid,unitId);
        //判断辨识起止时间
        recordWrapper.eq(EhsUnitIdentificationRecord::getTmtype,tmtype);
        recordWrapper.ge(EhsUnitIdentificationRecord::getTmbegin, beginTime);
        recordWrapper.le(EhsUnitIdentificationRecord::getTmend, endTime);
        recordWrapper.orderByAsc(EhsUnitIdentificationRecord::getUpdatetm);
        return repository.selectOne(recordWrapper);
    }

    /**
     * 根据单元编码查询单元危险源辨识记录
     *
     * @param unitId 单元ID
     * @return List<EhsUnitIdentificationRecord>
     * @author QuCheng Tech
     * @since 2024/6/28
     */
    public List<EhsUnitIdentificationRecord> getRecordsByUnitId(String unitId){
        LambdaQueryWrapper<EhsUnitIdentificationRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(EhsUnitIdentificationRecord::getUnitid,unitId);
        recordWrapper.orderByAsc(EhsUnitIdentificationRecord::getUpdatetm);
        return repository.selectList(recordWrapper);
    }

    /**
     * 新增单元危险源辨识记录
     * 
     * @param entity
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/6/28
     */
    public String addRecord(EhsUnitIdentificationRecord entity){
        if (entity == null) return QCUnifyReturnValue.Warn("对象不能为空");
        if (StringUtils.isBlank(entity.getUnitid())) return QCUnifyReturnValue.Warn("单元ID不能为空");
        
        if (StringUtils.isBlank(entity.getRecordid())) entity.setRecordid(IdentifierUtil.randomUUID());
        
        if (repository.insert(entity) < 0x1){
            return QCUnifyReturnValue.Warn("保存失败");
        }
        return QCUnifyReturnValue.Success();
    }

    /**
     * 修改单元危险源辨识记录
     *
     * @param entity
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/6/28
     */
    public String updateRecord(EhsUnitIdentificationRecord entity){
        if (entity == null) return QCUnifyReturnValue.Warn("对象不能为空");
        if (StringUtils.isBlank(entity.getUnitid())) return QCUnifyReturnValue.Warn("单元ID不能为空");
        
        if (!recordIsExist(entity.getRecordid())) return QCUnifyReturnValue.Warn("记录不存在");
        
        repository.updateById(entity);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 删除指定单元、指定周期的单元危险源辨识记录
     * 
     * @param unitId 单元ID
     * @param begintm 辨识周期开始时间
     * @param endtm 辨识周期结束时间
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/7/1
     */
    public String deleteRecord(String unitId,Date begintm,Date endtm){
        LambdaQueryWrapper<EhsUnitIdentificationRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsUnitIdentificationRecord::getUnitid,unitId);
        wrapper.ge(EhsUnitIdentificationRecord::getTmbegin,begintm);
        wrapper.le(EhsUnitIdentificationRecord::getTmend,endtm);
        
        repository.delete(wrapper);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 查询危险源台账 -- 查询结果按单元显示
     * @param condition 查询条件
     * @param deptIds 当前用户所属部门ids
     * @param orgCode 当前用户所属组织编码
     * @return QueryHazardAccountResultDto
     * @author QuCheng Tech
     * @since 2024/7/17
     */
    public QueryHazardAccountResultDto queryAccountByUnit(QueryHazardAccountConditionDto condition,
                                                    List<Integer> deptIds,
                                                    String orgCode) throws QCPromptException {
        //1.判断查询条件
        if (condition == null) throw new QCPromptException("查询条件不能为空");
        if (StringUtils.isBlank(condition.getBegintm())) throw new QCPromptException("开始时间不能为空");
        if (StringUtils.isBlank(condition.getEndtm())) throw new QCPromptException("结束时间不能为空");

        //2.查询时间转换处理
        Date beginDate = null;
        Date endDate = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getBegintm())) {
            try {
                beginDate = DateUtil.parseDate(condition.getBegintm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的开始日期转换错误");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(condition.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的截止日期转换错误");
            }
        }

        Date beginTime = beginDate;
        Date endTime = endDate;
        if (condition.getTmtype() == null) condition.setTmtype(TIME_RANGE);
        if (condition.getTmtype() == TimeRangeLengthEnum.MONTH.getIndex()){
            //按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }else if (condition.getTmtype() == TimeRangeLengthEnum.QUARTER.getIndex()){
            //按季度：根据开始时间处理为开始时间所在季度的第一天，根据结束时间处理为结束时间所在季度最后一天
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x0, 0x1);
            int beginTimeMonth = DateUtil.getMonth(beginDate);
            if (beginTimeMonth >= 10)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x9, 0x1);
            else if (beginTimeMonth >= 7)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x6, 0x1);
            else if (beginTimeMonth >= 4)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x3, 0x1);

            //先计算结束时间所在季度的开始时间endtmbegin，再根据endtmbegin计算结束时间
            Date endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x0, 0x1);
            int endTimeMonth = DateUtil.getMonth(endDate);
            if (endTimeMonth >= 10)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x9, 0x1);
            else if (endTimeMonth >= 7)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x6, 0x1);
            else if (endTimeMonth >= 4)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x3, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endtmbegin, 0x3), -1);
        }else{
            //默认按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }

        //3.获取当前用户所属组织的单元信息集合，无单元信息直接返回null
        LambdaQueryWrapper<EhsUnitBasic> unitWrapper = new LambdaQueryWrapper<>();
        unitWrapper.eq(EhsUnitBasic::getOrgcode,orgCode);
        unitWrapper.orderByAsc(EhsUnitBasic::getOdr,EhsUnitBasic::getUnitname);
        List<EhsUnitBasic> unitBasics = unitBasicRepository.selectList(unitWrapper);
        if (CollectionUtils.isEmpty(unitBasics)) return null;
        
        //4.根据单元ID集合查询危险源基础信息集合
        List<String> unitIds = unitBasics.stream().map(EhsUnitBasic::getUnitid).collect(Collectors.toList());
        List<EhsHazardBasicDto> hazardBasicDtos = hazardBasicService.getByUnitIds(unitIds);
        
        //5.将单元集合构建为查询结果项items树型结构
        List<QueryHazardAccountResultItemDto> items = new ArrayList<>();
        //获取根节点单元
        List<EhsUnitBasic> rootUnits = unitBasics.stream().filter(p -> StringUtils.isEmpty(p.getParentid())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(rootUnits)){
            items = getResultSubItems(condition,unitBasics,rootUnits,hazardBasicDtos);
        }
        
        //6.递归筛选items树型结构中符合查询条件的查询结果，自下而上开始筛选（从最底层）
        Iterator<QueryHazardAccountResultItemDto> rootLevelIterator = items.iterator();
        while (rootLevelIterator.hasNext()){
            QueryHazardAccountResultItemDto rootlevel = rootLevelIterator.next();
            //6.1 递归筛选子级
            if (rootlevel.getChildren() != null && rootlevel.getChildren().size() > 0x0){
                filterSubResult(rootlevel,condition,deptIds);
            }
            //6.2 筛选当前层级
            //是否移除当前层级单元
            boolean isRemoveRootLevel = false;
            //根据数据类型不同进行处理
            if (rootlevel.getType() == 1){
                //筛选单元信息
                //判断是否包含子级单元
                //如果单元编码不为空的情况，匹配了再判断是否包含子级单元，不包含则移除子级单元
                if (StringUtils.isNotBlank(condition.getUnitid())){
                    if (rootlevel.getId().equals(condition.getUnitid())){
                        if (!condition.getIncludechilds()){
                            if (rootlevel.getChildren() != null && rootlevel.getChildren().size() > 0x0){
                                Iterator<QueryHazardAccountResultItemDto> subIterator = rootlevel.getChildren().iterator();
                                while (subIterator.hasNext()){
                                    QueryHazardAccountResultItemDto subIteratorLevel = subIterator.next();
                                    if (subIteratorLevel.getType() == 1) subIterator.remove();
                                }
                            }
                        }
                    }else {
                        //单元编码不匹配移除当前层级
                        isRemoveRootLevel = true;
                    }
                }else{
                    //如果单元编码为空，判断是否包含子级单元，不包含则移除子级单元
                    if (!condition.getIncludechilds()){
                        if (rootlevel.getChildren() != null && rootlevel.getChildren().size() > 0x0){
                            Iterator<QueryHazardAccountResultItemDto> subIterator = rootlevel.getChildren().iterator();
                            while (subIterator.hasNext()){
                                QueryHazardAccountResultItemDto subIteratorLevel = subIterator.next();
                                if (subIteratorLevel.getType() == 1) subIterator.remove();
                            }
                        }
                    }
                }

                //判断是否有子级单元，如果子级为空或者子级中没有单元才进行筛选
                //先判断是否有子级单元
                boolean hasSubUnit = false;//是否有子级单元，默认没有
                if (rootlevel.getChildren() != null && rootlevel.getChildren().size() > 0x0){
                    Iterator<QueryHazardAccountResultItemDto> subIterator = rootlevel.getChildren().iterator();
                    while (subIterator.hasNext()){
                        QueryHazardAccountResultItemDto subIteratorLevel = subIterator.next();
                        if (subIteratorLevel.getType() == 1) hasSubUnit = true;
                    }
                }

                //没有子级或者子级单元则筛选当前层级中符合查询条件的单元信息
                if (rootlevel.getChildren() == null || rootlevel.getChildren().size() == 0x0 || hasSubUnit == false){
                    //匹配是否为在建工程：为0表示false，为1表示true，为空或其他时表示不管该标记状态
                    if (StringUtils.isNotBlank(condition.getIsconstruction())){
                        if (condition.getIsconstruction().equals("0") || condition.getIsconstruction().equals("false")){
                            if (rootlevel.getIsconstruction() == true) isRemoveRootLevel = true;
                        }else if (condition.getIsconstruction().equals("1") || condition.getIsconstruction().equals("true")){
                            if (rootlevel.getIsconstruction() == false) isRemoveRootLevel = true;
                        }
                    }
                    //是否根据用户部门进行过滤:为true表示根据当前用户所关联部门对单元进行筛选过滤，为false表示不过滤
                    if (condition.getIsdept()){
                        if (CollectionUtils.isNotEmpty(deptIds)){
                            boolean deptIsExist = false;//level4的部门是否匹配用户部门
                            for (Integer deptId : deptIds){
                                if (deptId == rootlevel.getDeptid()){
                                    deptIsExist = true;
                                }
                            }
                            if (!deptIsExist) isRemoveRootLevel = true;
                        }
                    }
                    //关键字匹配单元名称  第一层为单元，如果没有子级才进行关键字匹配
                    if (rootlevel.getChildren() == null || rootlevel.getChildren().size() == 0x0){
                        if (StringUtils.isNotBlank(condition.getKeywords())){
                            if (!(rootlevel.getName().contains(condition.getKeywords()))
                            ){
                                isRemoveRootLevel = true;
                            }
                        }
                    }

                    if (isRemoveRootLevel) rootLevelIterator.remove();
                }

            }else{
                //不处理
            }
        }

        //7.定义查询返回结果对象
        QueryHazardAccountResultDto result = new QueryHazardAccountResultDto();
        result.setItems(items);
        
        //8.统计各数量合计值
        totalStatisticalValue(items,result);
        
        //9.返回结果项
        return result;
    }

    /**
     * 统计结果项中的各个层级的各数量合计值
     * 只统计存在的危险源数量
     * 
     * @param items 树型结果项DTO
     * @param result 返回结果项
     * @author QuCheng Tech
     * @since 2024/7/19
     */
    private void totalStatisticalValue(List<QueryHazardAccountResultItemDto> items, QueryHazardAccountResultDto result){
        
        Integer general1 = 0x0,major1 = 0x0,level11 = 0x0,level12 = 0x0,level13 = 0x0,level14 = 0x0,
                general2 = 0x0,major2 = 0x0,level21 = 0x0,level22 = 0x0,level23 = 0x0,level24 = 0x0;
        
        if (CollectionUtils.isNotEmpty(items)){
            for (QueryHazardAccountResultItemDto itemDto : items){
                //第一层计数
                if (itemDto.getType() == 3){
                    if (itemDto.getHazard() != null){
                        EhsHazardFullInfoDto hazard = itemDto.getHazard();
                        if (hazard.getIdentification() != null){
                            if (hazard.getIdentification().getFinalresult() != null && 
                                    hazard.getIdentification().getFinalresult() == 3){
                                //第一类危险源
                                if (hazard.getIdentification().getIsmajor() != null){
                                    if (hazard.getIdentification().getIsmajor()) major1 += 1;
                                    else general1 += 1;
                                }
                                if (hazard.getEvaluation() != null && hazard.getEvaluation().getRisklevel() != null){
                                    if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.LOW.getIndex()) level11 += 1;
                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GENERAL.getIndex()) level12 += 1;
                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GREATER.getIndex()) level13 += 1;
                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.MAJOR.getIndex()) level14 += 1;
                                }
                            } else if (hazard.getIdentification().getFinalresult() != null && 
                                    hazard.getIdentification().getFinalresult() == 4){
                                //第二类危险源
                                if (hazard.getIdentification().getIsmajor() != null){
                                    if (hazard.getIdentification().getIsmajor()) major2 += 1;
                                    else general2 += 1;
                                }
                                if (hazard.getEvaluation() != null && hazard.getEvaluation().getRisklevel() != null){
                                    if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.LOW.getIndex()) level21 += 1;
                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GENERAL.getIndex()) level22 += 1;
                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GREATER.getIndex()) level23 += 1;
                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.MAJOR.getIndex()) level24 += 1;
                                }
                            }
                        }
                    }
                }
                
                //第二层计数
                if (itemDto.getChildren() != null && itemDto.getChildren().size() > 0x0){
                    for (QueryHazardAccountResultItemDto child1 : itemDto.getChildren()){
                        if (child1.getType() == 3){
                            if (child1.getHazard() != null){
                                EhsHazardFullInfoDto hazard = child1.getHazard();
                                if (hazard.getIdentification() != null){
                                    if (hazard.getIdentification().getFinalresult() != null &&
                                            hazard.getIdentification().getFinalresult() == 3){
                                        //第一类危险源
                                        if (hazard.getIdentification().getIsmajor() != null){
                                            if (hazard.getIdentification().getIsmajor()) major1 += 1;
                                            else general1 += 1;
                                        }
                                        if (hazard.getEvaluation() != null && hazard.getEvaluation().getRisklevel() != null){
                                            if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.LOW.getIndex()) level11 += 1;
                                            else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GENERAL.getIndex()) level12 += 1;
                                            else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GREATER.getIndex()) level13 += 1;
                                            else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.MAJOR.getIndex()) level14 += 1;
                                        }
                                    } else if (hazard.getIdentification().getFinalresult() != null &&
                                            hazard.getIdentification().getFinalresult() == 4){
                                        //第二类危险源
                                        if (hazard.getIdentification().getIsmajor() != null){
                                            if (hazard.getIdentification().getIsmajor()) major2 += 1;
                                            else general2 += 1;
                                        }
                                        if (hazard.getEvaluation() != null && hazard.getEvaluation().getRisklevel() != null){
                                            if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.LOW.getIndex()) level21 += 1;
                                            else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GENERAL.getIndex()) level22 += 1;
                                            else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GREATER.getIndex()) level23 += 1;
                                            else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.MAJOR.getIndex()) level24 += 1;
                                        }
                                    }
                                }
                            }
                        }
                        
                        //第三层计数
                        if (child1.getChildren() != null && child1.getChildren().size() > 0x0){
                            for (QueryHazardAccountResultItemDto child2 : child1.getChildren()){
                                if (child2.getType() == 3){
                                    if (child2.getHazard() != null){
                                        EhsHazardFullInfoDto hazard = child2.getHazard();
                                        if (hazard.getIdentification() != null){
                                            if (hazard.getIdentification().getFinalresult() != null &&
                                                    hazard.getIdentification().getFinalresult() == 3){
                                                //第一类危险源
                                                if (hazard.getIdentification().getIsmajor() != null){
                                                    if (hazard.getIdentification().getIsmajor()) major1 += 1;
                                                    else general1 += 1;
                                                }
                                                if (hazard.getEvaluation() != null && hazard.getEvaluation().getRisklevel() != null){
                                                    if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.LOW.getIndex()) level11 += 1;
                                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GENERAL.getIndex()) level12 += 1;
                                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GREATER.getIndex()) level13 += 1;
                                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.MAJOR.getIndex()) level14 += 1;
                                                }
                                            } else if (hazard.getIdentification().getFinalresult() != null &&
                                                    hazard.getIdentification().getFinalresult() == 4){
                                                //第二类危险源
                                                if (hazard.getIdentification().getIsmajor() != null){
                                                    if (hazard.getIdentification().getIsmajor()) major2 += 1;
                                                    else general2 += 1;
                                                }
                                                if (hazard.getEvaluation() != null && hazard.getEvaluation().getRisklevel() != null){
                                                    if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.LOW.getIndex()) level21 += 1;
                                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GENERAL.getIndex()) level22 += 1;
                                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.GREATER.getIndex()) level23 += 1;
                                                    else if (hazard.getEvaluation().getRisklevel() == EhsRiskLevelEnum.MAJOR.getIndex()) level24 += 1;
                                                }
                                            }
                                        }
                                    }
                                }
                                
                                //第四层。。。
                                
                                
                            }
                        }
                    }
                }
            }
        }
        result.setGeneral1(general1);
        result.setMajor1(major1);
        result.setLevel11(level11);
        result.setLevel12(level12);
        result.setLevel13(level13);
        result.setLevel14(level14);
        result.setGeneral2(general2);
        result.setMajor2(major2);
        result.setLevel21(level21);
        result.setLevel22(level22);
        result.setLevel23(level23);
        result.setLevel24(level24);
    }

    /**
     * 递归筛选符合查询条件的危险源台账-按单元显示
     * 
     * @param rootLevel 父层级单元
     * @param condition 查询条件
     * @param deptIds 用户所属部门ID集合
     * @author QuCheng Tech
     * @since 2024/7/18
     */
    private void filterSubResult(QueryHazardAccountResultItemDto rootLevel, 
                                          QueryHazardAccountConditionDto condition, 
                                          List<Integer> deptIds){
        Iterator<QueryHazardAccountResultItemDto> subLevelIterator = rootLevel.getChildren().iterator();
        while (subLevelIterator.hasNext()){
            QueryHazardAccountResultItemDto subLevel = subLevelIterator.next();

            //1.递归筛选子级
            if (subLevel.getChildren() != null && subLevel.getChildren().size() > 0x0){
                filterSubResult(subLevel,condition,deptIds);
            }
            
            //2.筛选当前层级
            //是否移除当前层级
            boolean isRemoveSubLevel = false;
            //2.1 根据数据类型不同进行处理筛选
            if (subLevel.getType() == 1){
                //筛选单元信息
                //判断是否包含子级单元
                //如果单元编码不为空的情况，匹配了再判断是否包含子级单元，不包含则移除子级单元
                if (StringUtils.isNotBlank(condition.getUnitid())){
                    if (subLevel.getId().equals(condition.getUnitid())){
                        if (!condition.getIncludechilds()){
                            if (subLevel.getChildren() != null && subLevel.getChildren().size() > 0x0){
                                Iterator<QueryHazardAccountResultItemDto> subIterator = subLevel.getChildren().iterator();
                                while (subIterator.hasNext()){
                                    QueryHazardAccountResultItemDto subIteratorLevel = subIterator.next();
                                    if (subIteratorLevel.getType() == 1) subIterator.remove();
                                }
                            }
                        }
                    }else {
                        //单元编码不匹配移除当前层级
                        isRemoveSubLevel = true;
                    }
                }else{
                    //如果单元编码为空，判断是否包含子级单元，不包含则移除子级单元
                    if (!condition.getIncludechilds()){
                        if (subLevel.getChildren() != null && subLevel.getChildren().size() > 0x0){
                            Iterator<QueryHazardAccountResultItemDto> subIterator = subLevel.getChildren().iterator();
                            while (subIterator.hasNext()){
                                QueryHazardAccountResultItemDto subIteratorLevel = subIterator.next();
                                if (subIteratorLevel.getType() == 1) subIterator.remove();
                            }
                        }
                    }
                }

                //判断是否有子级单元，如果子级为空或者子级中没有单元才进行筛选
                //先判断是否有子级单元
                boolean hasSubUnit = false;//是否有子级单元，默认没有
                if (subLevel.getChildren() != null && subLevel.getChildren().size() > 0x0){
                    Iterator<QueryHazardAccountResultItemDto> subIterator = subLevel.getChildren().iterator();
                    while (subIterator.hasNext()){
                        QueryHazardAccountResultItemDto subIteratorLevel = subIterator.next();
                        if (subIteratorLevel.getType() == 1) hasSubUnit = true;
                    }
                }
                
                //没有子级单元则筛选当前层级
                if (subLevel.getChildren() == null || subLevel.getChildren().size() == 0x0 || hasSubUnit == false){
                    //匹配是否为在建工程：为0表示false，为1表示true，为空或其他时表示不管该标记状态
                    if (StringUtils.isNotBlank(condition.getIsconstruction())){
                        if (condition.getIsconstruction().equals("0") || condition.getIsconstruction().equals("false")){
                            if (subLevel.getIsconstruction() == true) isRemoveSubLevel = true;
                        }else if (condition.getIsconstruction().equals("1") || condition.getIsconstruction().equals("true")){
                            if (subLevel.getIsconstruction() == false) isRemoveSubLevel = true;
                        }
                    }
                    //是否根据用户部门进行过滤:为true表示根据当前用户所关联部门对单元进行筛选过滤，为false表示不过滤
                    if (condition.getIsdept()){
                        if (CollectionUtils.isNotEmpty(deptIds)){
                            boolean deptIsExist = false;//level4的部门是否匹配用户部门
                            for (Integer deptId : deptIds){
                                if (deptId == subLevel.getDeptid()){
                                    deptIsExist = true;
                                }
                            }
                            if (!deptIsExist) isRemoveSubLevel = true;
                        }
                    }
                    //关键字匹配单元名称
                    if (StringUtils.isNotBlank(condition.getKeywords())){
                        if (!(subLevel.getName().contains(condition.getKeywords()))
                        ){
                            isRemoveSubLevel = true;
                        }
                    }
                    
                    if (isRemoveSubLevel) subLevelIterator.remove();
                }

            }else if (subLevel.getType() == 3){
                //筛选危险源信息
                //先判断是否有子级，子级中是否有危险源，如果子级为空或者子级中没有危险源才进行当前层级的筛选
                //如果有子级先判断是否有子级单元
                boolean hasSubHazard = false;//是否有子级危险源，默认没有
                if (subLevel.getChildren() != null && subLevel.getChildren().size() > 0x0){
                    Iterator<QueryHazardAccountResultItemDto> subIterator = subLevel.getChildren().iterator();
                    while (subIterator.hasNext()){
                        QueryHazardAccountResultItemDto subIteratorLevel = subIterator.next();
                        if (subIteratorLevel.getType() == 3) hasSubHazard = true;
                    }
                }
                //没有子级危险源则筛选当前层级
                if (subLevel.getChildren() == null || subLevel.getChildren().size() == 0x0 || hasSubHazard == false){
                    if (subLevel.getHazard() != null){
                        EhsHazardFullInfoDto hazard = subLevel.getHazard();
                        
                        //匹配危险源级别：为0表示false(一般)，为1表示true(重大)，为空或其他时表示不管该标记状态
                        if (StringUtils.isNotBlank(condition.getIsmajor())){
                            if (hazard.getBasic() != null){
                                if (hazard.getBasic().getIsmajor() != null){
                                    if (condition.getIsmajor().equals("0") || condition.getIsmajor().equals("false")){
                                        if (hazard.getBasic().getIsmajor() == true) isRemoveSubLevel = true;
                                    }else if (condition.getIsmajor().equals("1") || condition.getIsmajor().equals("true")){
                                        if (hazard.getBasic().getIsmajor() == false) isRemoveSubLevel = true;
                                    }
                                }else {
                                    isRemoveSubLevel = true;
                                }
                            }
                        }

                        //匹配危险源类别：为0表示false(第一类危险源)，为1表示true(第二类危险源)，为空或其他时表示不管该标记状态;
                        if (StringUtils.isNotBlank(condition.getIshidden())){
                            if (hazard.getIdentification() != null){
                                if (hazard.getIdentification().getFinalresult() != null){
                                    if (condition.getIshidden().equals("0") || condition.getIshidden().equals("false")){
                                        if (hazard.getIdentification().getFinalresult() != 3) isRemoveSubLevel = true;
                                    } else if (condition.getIshidden().equals("1") || condition.getIshidden().equals("true")) {
                                        if (hazard.getIdentification().getFinalresult() != 4) isRemoveSubLevel = true;
                                    }
                                }else {
                                    isRemoveSubLevel = true;
                                }
                            }
                        }

                        //匹配危险源风险等级
                        if (StringUtils.isNotBlank(condition.getRisklevel())){
                            if (hazard.getEvaluation() != null){
                                if (hazard.getEvaluation().getRisklevel() != null){
                                    if (Integer.parseInt(condition.getRisklevel()) != hazard.getEvaluation().getRisklevel())
                                        isRemoveSubLevel = true;
                                }else {
                                    isRemoveSubLevel = true;
                                }
                            }
                        }
                    }
                    
                    //关键字匹配危险源名称
                    if (StringUtils.isNotBlank(condition.getKeywords())){
                        if (!(subLevel.getName().contains(condition.getKeywords()))
                        ){
                            isRemoveSubLevel = true;
                        }
                    }

                    if (isRemoveSubLevel) subLevelIterator.remove();
                }
            }else{
                //不处理
            }

        }
    }

    /**
     * 递归处理按单元显示危险源台树型结果项
     * 
     * @param condition 查询条件
     * @param unitBasics 当前用户所属组织的单元信息集合
     * @param parentUnits 父级单元信息集合
     * @param hazardBasicDtos 所有单元的危险源信息集合
     * @return List<QueryHazardAccountResultItemDto>
     * @throws QCPromptException
     * @author QuCheng Tech
     * @since 2024/7/17
     */
    private List<QueryHazardAccountResultItemDto> getResultSubItems(QueryHazardAccountConditionDto condition,
                                                                    List<EhsUnitBasic> unitBasics,
                                                                    List<EhsUnitBasic> parentUnits,
                                                                    List<EhsHazardBasicDto> hazardBasicDtos) throws QCPromptException {
        //1.定义结果项集合
        List<QueryHazardAccountResultItemDto> items = new ArrayList<>();
        
        if (CollectionUtils.isEmpty(unitBasics)) return null;

        //2.递归构建单元树型结构
        if (CollectionUtils.isNotEmpty(parentUnits)){
            for (EhsUnitBasic pUnit : parentUnits){
                //2.1 设置单元信息
                QueryHazardAccountResultItemDto pUnitItem = new QueryHazardAccountResultItemDto();
                pUnitItem.setId(pUnit.getUnitid());
                pUnitItem.setName(pUnit.getUnitname());
                pUnitItem.setType(1); //数据类型：1-单元信息，2-类别信息，3-危险源信息
                pUnitItem.setIsconstruction(pUnit.getIsconstruction());
                pUnitItem.setDeptid(pUnit.getDeptid());

                //2.2 设置单元的危险源信息
                List<QueryHazardAccountResultItemDto> subItems = new ArrayList<>();
                //获取当前单元的危险源信息，设置到当前单元的子级中
                if (CollectionUtils.isNotEmpty(hazardBasicDtos)){
                    //根据当前单元id过滤危险源
                    List<EhsHazardBasicDto> hazardsOfpUnit = hazardBasicDtos.stream().filter(p -> 
                            pUnit.getUnitid().equals(p.getUnitcode())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(hazardsOfpUnit)){
                        for (EhsHazardBasicDto hazardOfpUnit:hazardsOfpUnit){
                            QueryHazardAccountResultItemDto hazardPItem = new QueryHazardAccountResultItemDto();
                            hazardPItem.setId(hazardOfpUnit.getHazardid());
                            hazardPItem.setName(hazardOfpUnit.getHazardname());
                            hazardPItem.setType(3);
                            //获取危险源完整信息
                            EhsHazardFullInfoConditionDto conditionDto = new EhsHazardFullInfoConditionDto();
                            conditionDto.setId(hazardOfpUnit.getHazardid());
                            conditionDto.setTmtype(condition.getTmtype());
                            conditionDto.setBegintm(condition.getBegintm());
                            conditionDto.setEndtm(condition.getEndtm());
                            EhsHazardFullInfoDto hazard = hazardBasicService.getFullInfo(conditionDto);
                            if (Objects.nonNull(hazard)) hazardPItem.setHazard(hazard);
                            subItems.add(hazardPItem);
                        }
                    }
                }
                
                //2.3 设置单元的子单元信息
                // 获取子级单元信息集合
                List<EhsUnitBasic> subUnits = unitBasics.stream().filter(p -> pUnit.getUnitid().equals(p.getParentid())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(subUnits)){
                    for (EhsUnitBasic subUnit : subUnits){
                        QueryHazardAccountResultItemDto subUnitItem = new QueryHazardAccountResultItemDto();
                        subUnitItem.setId(subUnit.getUnitid());
                        subUnitItem.setName(subUnit.getUnitname());
                        subUnitItem.setType(1);
                        subUnitItem.setIsconstruction(subUnit.getIsconstruction());
                        subUnitItem.setDeptid(subUnit.getDeptid());

                        List<QueryHazardAccountResultItemDto> hazardSubItems = new ArrayList<>();
                        //获取当前单元的危险源信息，设置到当前单元的子级中
                        if (CollectionUtils.isNotEmpty(hazardBasicDtos)){
                            //根据当前单元id过滤危险源
                            List<EhsHazardBasicDto> hazardsOfsubUnit = hazardBasicDtos.stream().filter(p ->
                                    subUnit.getUnitid().equals(p.getUnitcode())).collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(hazardsOfsubUnit)){
                                for (EhsHazardBasicDto hazardOfsubUnit:hazardsOfsubUnit){
                                    QueryHazardAccountResultItemDto HazardSubItem = new QueryHazardAccountResultItemDto();
                                    HazardSubItem.setId(hazardOfsubUnit.getHazardid());
                                    HazardSubItem.setName(hazardOfsubUnit.getHazardname());
                                    HazardSubItem.setType(3);
                                    //获取危险源完整信息
                                    EhsHazardFullInfoConditionDto conditionDto = new EhsHazardFullInfoConditionDto();
                                    conditionDto.setId(hazardOfsubUnit.getHazardid());
                                    conditionDto.setTmtype(condition.getTmtype());
                                    conditionDto.setBegintm(condition.getBegintm());
                                    conditionDto.setEndtm(condition.getEndtm());
                                    EhsHazardFullInfoDto hazard = hazardBasicService.getFullInfo(conditionDto);
                                    if (Objects.nonNull(hazard)) HazardSubItem.setHazard(hazard);
                                    hazardSubItems.add(HazardSubItem);
                                }
                                subUnitItem.setChildren(hazardSubItems);
                            }
                        }
                        
                        subItems.add(subUnitItem);
                    }
                    //3.递归获取子级单元信息集合
                    getResultSubItems(condition,unitBasics,subUnits,hazardBasicDtos);
                }
                pUnitItem.setChildren(subItems);
                
                items.add(pUnitItem);
            }
        }
        return items;
    }

    /**
     * 查询危险源台账 -- 查询结果按危险源类别显示
     * @param condition 查询条件
     * @return QueryHazardAccountResultDto
     * @author QuCheng Tech
     * @since 2024/7/22
     */
    public QueryHazardAccountResultDto queryAccountByHazardCtg(QueryHazardAccountConditionDto condition) throws QCPromptException {

        //1.判断查询条件
        if (condition == null) throw new QCPromptException("查询条件不能为空");
        if (StringUtils.isBlank(condition.getBegintm())) throw new QCPromptException("开始时间不能为空");
        if (StringUtils.isBlank(condition.getEndtm())) throw new QCPromptException("结束时间不能为空");

        //2.查询时间转换处理
        Date beginDate = null;
        Date endDate = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getBegintm())) {
            try {
                beginDate = DateUtil.parseDate(condition.getBegintm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的开始日期转换错误");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(condition.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(condition.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的截止日期转换错误");
            }
        }

        Date beginTime = beginDate;
        Date endTime = endDate;
        if (condition.getTmtype() == null) condition.setTmtype(TIME_RANGE);
        if (condition.getTmtype() == TimeRangeLengthEnum.MONTH.getIndex()){
            //按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }else if (condition.getTmtype() == TimeRangeLengthEnum.QUARTER.getIndex()){
            //按季度：根据开始时间处理为开始时间所在季度的第一天，根据结束时间处理为结束时间所在季度最后一天
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x0, 0x1);
            int beginTimeMonth = DateUtil.getMonth(beginDate);
            if (beginTimeMonth >= 10)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x9, 0x1);
            else if (beginTimeMonth >= 7)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x6, 0x1);
            else if (beginTimeMonth >= 4)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x3, 0x1);

            //先计算结束时间所在季度的开始时间endtmbegin，再根据endtmbegin计算结束时间
            Date endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x0, 0x1);
            int endTimeMonth = DateUtil.getMonth(endDate);
            if (endTimeMonth >= 10)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x9, 0x1);
            else if (endTimeMonth >= 7)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x6, 0x1);
            else if (endTimeMonth >= 4)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x3, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endtmbegin, 0x3), -1);
        }else{
            //默认按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }
        
        //3.根据辨识起止时间查询辨识记录
        List<EhsHazardPreventrecord> identifications = hazardPreventrecordService.getRecords(null,
                EhsHazardPreventTypeEnum.IDENTIFICATION.getIndex(),beginTime,endTime,condition.getTmtype());

        //4.获取危险源ID集合，查询危险源基础信息集合
        List<String> hazardIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(identifications)) 
            hazardIds = identifications.stream().map(EhsHazardPreventrecord::getHazardid).distinct().collect(Collectors.toList());
        List<EhsHazardBasicDto> hazards = hazardBasicService.getHazardBasicInfoList(hazardIds);

        //5.使用危险源基础信息集合构建为树型结构（第一层级为类别信息，第二层级为危险源信息）
        List<QueryHazardAccountResultItemDto> items = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(hazards)){
            //5.1 将危险源类别设置树型结构第一层级（类别代码为空的设置为对应类别的名称（手动新增的危险源））
            List<QueryHazardAccountResultItemDto> rootItems = new ArrayList<>();
            for (EhsHazardBasicDto hazardBasicDto : hazards){
                QueryHazardAccountResultItemDto rootItem = new QueryHazardAccountResultItemDto();
                if (StringUtils.isNotBlank(hazardBasicDto.getCategorycode())) rootItem.setId(hazardBasicDto.getCategorycode());
                else rootItem.setId(hazardBasicDto.getCategoryname());
                rootItem.setName(hazardBasicDto.getCategoryname());
                rootItem.setType(2);
                rootItems.add(rootItem);
            }
            //5.2 将第一层级的危险源类别去重
            items = rootItems.stream().distinct().collect(Collectors.toList());

            //5.3 处理设置子层级（危险源信息）
            for (QueryHazardAccountResultItemDto rootItem : items){
                List<QueryHazardAccountResultItemDto> subItems = new ArrayList<>();
                for (EhsHazardBasicDto hazardBasicDto : hazards){
                    String ctgCode = "";
                    if (StringUtils.isNotBlank(hazardBasicDto.getCategorycode())) ctgCode = hazardBasicDto.getCategorycode();
                    else ctgCode = hazardBasicDto.getCategoryname();
                    
                    if (rootItem.getId().equals(ctgCode)){
                        QueryHazardAccountResultItemDto subItem = new QueryHazardAccountResultItemDto();
                        subItem.setId(hazardBasicDto.getHazardid());
                        subItem.setName(hazardBasicDto.getHazardname());
                        subItem.setType(3);
                        //获取设置危险源完整信息
                        EhsHazardFullInfoConditionDto conditionDto = new EhsHazardFullInfoConditionDto();
                        conditionDto.setId(hazardBasicDto.getHazardid());
                        conditionDto.setTmtype(condition.getTmtype());
                        conditionDto.setBegintm(condition.getBegintm());
                        conditionDto.setEndtm(condition.getEndtm());
                        EhsHazardFullInfoDto hazard = hazardBasicService.getFullInfo(conditionDto);
                        if (Objects.nonNull(hazard)) subItem.setHazard(hazard);
                        subItems.add(subItem);
                    }
                }
                rootItem.setChildren(subItems);
            }
        }

        //6.筛选符合查询条件的查询结果
        Iterator<QueryHazardAccountResultItemDto> rootLevelIterator = items.iterator();
        while (rootLevelIterator.hasNext()){
            QueryHazardAccountResultItemDto rootlevel = rootLevelIterator.next();
            //筛选子级危险源信息
            if (rootlevel.getChildren() != null && rootlevel.getChildren().size() > 0x0){
                Iterator<QueryHazardAccountResultItemDto> subLevelIterator = rootlevel.getChildren().iterator();
                while (subLevelIterator.hasNext()){
                    QueryHazardAccountResultItemDto subLevel = subLevelIterator.next();

                    //是否移除当前层级
                    boolean isRemoveSubLevel = false;
                    // 根据数据类型不同进行处理筛选
                    if (subLevel.getType() == 3){
                        //筛选危险源信息
                        if (subLevel.getHazard() != null){
                            EhsHazardFullInfoDto hazard = subLevel.getHazard();
                            
                            //匹配单元编码
                            if (StringUtils.isNotBlank(condition.getUnitid())){
                                if (hazard.getBasic() != null){
                                    if (hazard.getBasic().getUnitcode() != null){
                                        if (!condition.getUnitid().equals(hazard.getBasic().getUnitcode())){
                                            isRemoveSubLevel = true;
                                        }
                                    }else {
                                        isRemoveSubLevel = true;
                                    }
                                }
                            }
                            //匹配危险源级别：为0表示false(一般)，为1表示true(重大)，为空或其他时表示不管该标记状态
                            if (StringUtils.isNotBlank(condition.getIsmajor())){
                                if (hazard.getBasic() != null){
                                    if (hazard.getBasic().getIsmajor() != null){
                                        if (condition.getIsmajor().equals("0") || condition.getIsmajor().equals("false")){
                                            if (hazard.getBasic().getIsmajor() == true) isRemoveSubLevel = true;
                                        }else if (condition.getIsmajor().equals("1") || condition.getIsmajor().equals("true")){
                                            if (hazard.getBasic().getIsmajor() == false) isRemoveSubLevel = true;
                                        }
                                    }else {
                                        isRemoveSubLevel = true;
                                    }
                                }
                            }
                            //匹配危险源类别：为0表示false(第一类危险源)，为1表示true(第二类危险源)，为空或其他时表示不管该标记状态;
                            if (StringUtils.isNotBlank(condition.getIshidden())){
                                if (hazard.getIdentification() != null){
                                    if (hazard.getIdentification().getFinalresult() != null){
                                        if (condition.getIshidden().equals("0") || condition.getIshidden().equals("false")){
                                            if (hazard.getIdentification().getFinalresult() != 3) isRemoveSubLevel = true;
                                        } else if (condition.getIshidden().equals("1") || condition.getIshidden().equals("true")) {
                                            if (hazard.getIdentification().getFinalresult() != 4) isRemoveSubLevel = true;
                                        }
                                    }else {
                                        isRemoveSubLevel = true;
                                    }
                                }
                            }
                            //匹配危险源风险等级
                            if (StringUtils.isNotBlank(condition.getRisklevel())){
                                if (hazard.getEvaluation() != null){
                                    if (hazard.getEvaluation().getRisklevel() != null){
                                        if (Integer.parseInt(condition.getRisklevel()) != hazard.getEvaluation().getRisklevel())
                                            isRemoveSubLevel = true;
                                    }else {
                                        isRemoveSubLevel = true;
                                    }
                                }
                                
                            }
                        }
                        
                        //关键字匹配类别名称  第一层为类别，如果没有子级才进行关键字匹配 
                        if (StringUtils.isNotBlank(condition.getKeywords())){
                            if (!(subLevel.getName().contains(condition.getKeywords())))
                                isRemoveSubLevel = true;
                        }

                        if (isRemoveSubLevel) subLevelIterator.remove();
                    }else {
                        //不处理
                    }
                    
                }
            }
            
            //筛选当前层级
            //是否移除当前层级单元
            boolean isRemoveRootLevel = false;
            //根据数据类型不同进行处理
            if (rootlevel.getType() == 2){
               //筛选类别信息
                //没有子级时筛选当前层级
                if (rootlevel.getChildren() == null || rootlevel.getChildren().size() == 0x0){
                    //关键字匹配类别名称  第一层为类别，如果没有子级才进行关键字匹配 
                    if (StringUtils.isNotBlank(condition.getKeywords())){
                        if (!(rootlevel.getName().contains(condition.getKeywords())))
                            isRemoveRootLevel = true;
                    }
                    
                    if (isRemoveRootLevel) rootLevelIterator.remove();
                }
            }else {
                //不处理
            }
        }

        //7.定义设置查询返回结果对象
        QueryHazardAccountResultDto result = new QueryHazardAccountResultDto();
        result.setItems(items);
        
        //8.统计返回结果中各数量合计值
        totalStatisticalValue(items,result);
        
        //9.返回结果项
        return result;
    }

    /**
     * 修改指定单元指定周期的单元危险源辨识记录状态
     * 
     * @param dto 修改条件
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/7/26
     */
    public String editIdentificationStatus(EditUnitHazardStatusDto dto) {
        //1.条件判空
        if (dto == null) return QCUnifyReturnValue.Warn("条件不能为空");
        if (StringUtils.isBlank(dto.getUnitid())) return QCUnifyReturnValue.Warn("单元ID不能为空");
        if (StringUtils.isBlank(dto.getBegintm())) return QCUnifyReturnValue.Warn("辨识起始时间不能为空");
        if (StringUtils.isBlank(dto.getEndtm())) return QCUnifyReturnValue.Warn("辨识截止时间不能为空");

        //2.查询时间转换处理
        Date beginDate = null;
        Date endDate = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dto.getBegintm())) {
            try {
                beginDate = DateUtil.parseDate(dto.getBegintm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                return QCUnifyReturnValue.Warn("查询条件中的开始日期转换错误");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dto.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(dto.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                return QCUnifyReturnValue.Warn("查询条件中的截止日期转换错误");
            }
        }

        Date beginTime = beginDate;
        Date endTime = endDate;
        if (dto.getTmtype() == null) dto.setTmtype(TIME_RANGE);
        if (dto.getTmtype() == TimeRangeLengthEnum.MONTH.getIndex()){
            //按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }else if (dto.getTmtype() == TimeRangeLengthEnum.QUARTER.getIndex()){
            //按季度：根据开始时间处理为开始时间所在季度的第一天，根据结束时间处理为结束时间所在季度最后一天
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x0, 0x1);
            int beginTimeMonth = DateUtil.getMonth(beginDate);
            if (beginTimeMonth >= 10)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x9, 0x1);
            else if (beginTimeMonth >= 7)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x6, 0x1);
            else if (beginTimeMonth >= 4)
                beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), 0x3, 0x1);

            //先计算结束时间所在季度的开始时间endtmbegin，再根据endtmbegin计算结束时间
            Date endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x0, 0x1);
            int endTimeMonth = DateUtil.getMonth(endDate);
            if (endTimeMonth >= 10)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x9, 0x1);
            else if (endTimeMonth >= 7)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x6, 0x1);
            else if (endTimeMonth >= 4)
                endtmbegin = DateUtil.newDate(DateUtil.getYear(endDate), 0x3, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endtmbegin, 0x3), -1);
        }else{
            //默认按月
            beginTime = DateUtil.newDate(DateUtil.getYear(beginDate), DateUtil.getMonth(beginDate) - 1, 0x1);
            endTime = DateUtil.addDays(DateUtil.addMonths(endDate, 0x1), -1);
        }
        
        //3.修改指定辨识记录状态
        LambdaUpdateWrapper<EhsUnitIdentificationRecord> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(EhsUnitIdentificationRecord::getUnitid,dto.getUnitid());
        wrapper.eq(EhsUnitIdentificationRecord::getTmtype,dto.getTmtype());
        wrapper.ge(EhsUnitIdentificationRecord::getTmbegin, beginTime);
        wrapper.le(EhsUnitIdentificationRecord::getTmend, endTime);
        if (StringUtils.isNotBlank(dto.getStatus())){
            if (dto.getStatus().equals("0") || dto.getStatus().equals("false")) 
                wrapper.set(EhsUnitIdentificationRecord::getFlag,false);
            else if (dto.getStatus().equals("1") || dto.getStatus().equals("true"))
                wrapper.set(EhsUnitIdentificationRecord::getFlag,true);
        }
        
        repository.update(null,wrapper);
        
        return QCUnifyReturnValue.Success();
    }

    /**
     * 判断记录是否存在
     * 
     * @param recordId 记录ID
     * @return
     * @author QuCheng Tech
     * @since 2024/6/28
     */
    private boolean recordIsExist(String recordId){
        EhsUnitIdentificationRecord en = repository.selectById(recordId);
        if (Objects.nonNull(en)){
            return true;
        }
        return false;
    }
    
}
